package edu.uclm.esi.tysweb.ajedrez.actions;

import java.sql.SQLException;

import org.apache.http.HttpRequest;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import edu.uclm.esi.tysweb.ajedrez.dominio.GestorAjedrez;
import edu.uclm.esi.tysweb.ajedrez.dominio.Jugador;
import edu.uclm.esi.tysweb.ajedrez.exceptions.UserAlreadyExistingException;
import edu.uclm.esi.tysweb.ajedrez.utils.ValidatorUtil;

public class Registrar extends ActionSupport {
	private String email;
	private String pwd1, pwd2;
	private Exception exception;
	
	public String execute() {
		try {
			GestorAjedrez gestor=GestorAjedrez.get();
			gestor.registrar(email, pwd1);
			this.exception=null;
			return SUCCESS;
		} catch (Exception e) {
			ActionContext.getContext().getSession().put("exception", e);
			this.exception=e;
			return ERROR;
		}
	}
	
	@Override
	public void validate() {
		if (this.pwd1==null || this.pwd2==null || this.pwd1.length()==0 || this.pwd2.length()==0) {
			super.addFieldError("pwd1", "Las passwords deben coincidir");
		}
		if (!this.pwd1.equals(this.pwd2)) {
			super.addFieldError("pwd2", "Las passwords deben coincidir");
		}
		if (this.email==null || this.email.length()==0) {
			super.addFieldError("email", "El email no puede estar vac??o");
		}
		if (this.email!=null && this.email.length()>45) {
			super.addFieldError("email", "El email no puede tener m??s de 45 caracteres");
		}
		if (!ValidatorUtil.validateEmail(email))
			super.addFieldError("email", "La direcci??n de email es inv??lida");
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setPwd1(String pwd1) {
		this.pwd1 = pwd1;
	}

	public void setPwd2(String pwd2) {
		this.pwd2 = pwd2;
	}

	public String getResultado() {
		if (exception!=null)
			return exception.toString();
		return "OK";
	}
}
